/*
 * @Date: 2023-08-17 21:55:38
 * @LastEditors: Wangjun
 * @LastEditTime: 2023-10-08 10:43:46
 * @FilePath: \xr_node_calc\models\memory.go
 * @Description:
 */
package models

import (
	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/golib/lz4file"
	"gitee.com/hnxr_1/nodex"
	"github.com/ugorji/go/codec"
)

const (
	pathMemory     = "data/data.dat" //画布缓存
	pathNodeMemory = "data/node.dat" //算子缓存
)

type Memory struct {
	ID string
	V  float64
	NG bool
}

func (m *Memory) GetID() string {
	return m.ID
}

// saveMemory 保存报警的中间计算变量
func (m *Boss) saveNodeMemory() {
	mh := new(codec.MsgpackHandle)
	var data []byte
	err := codec.NewEncoderBytes(&data, mh).Encode(&m.nodeMems)
	if err != nil {
		logs.Warn("Encode msgpack", err.Error())
		return
	}

	err = lz4file.SaveLz4File(pathNodeMemory, data)
	if err != nil {
		logs.Warn("保存Msgpack文件错误", err.Error())
		return
	}
}

func (m *Boss) SaveMemory() {
	m.saveMemory()
	m.saveNodeMemory()
}

func (m *Boss) saveMemory() {
	mh := new(codec.MsgpackHandle)
	var data []byte
	err := codec.NewEncoderBytes(&data, mh).Encode(&m.memorys)
	if err != nil {
		logs.Warn("Encode msgpack", err.Error())
		return
	}

	err = lz4file.SaveLz4File(pathMemory, data)
	if err != nil {
		logs.Warn("保存Msgpack文件错误", err.Error())
		return
	}
}

// loadMemo 画布缓存的结果
func (m *Boss) loadMemory() (mp map[string]*Memory) {
	data, err := lz4file.LoadLz4File(pathMemory)
	if err != nil {
		logs.Warn(err.Error())
		return
	}
	mh := new(codec.MsgpackHandle)
	var mems []*Memory
	err = codec.NewDecoderBytes(data, mh).Decode(&mems)
	if err != nil {
		logs.Warn(err.Error())
		return
	}
	mp = map[string]*Memory{}
	for _, ae := range mems {
		mp[ae.ID] = ae
	}
	return
}

// loadNodeMemory 读取节点缓存的变量
func (m *Boss) loadNodeMemory() (mp map[string]*nodex.Memory) {
	data, err := lz4file.LoadLz4File(pathNodeMemory)
	if err != nil {
		logs.Warn(err.Error())
		return
	}
	mh := new(codec.MsgpackHandle)
	var mems []*nodex.Memory
	err = codec.NewDecoderBytes(data, mh).Decode(&mems)
	if err != nil {
		logs.Warn(err.Error())
		return
	}
	mp = map[string]*nodex.Memory{}
	for _, ae := range mems {
		mp[ae.UID] = ae
	}
	return
}
